package handler

import (
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	jwt "github.com/golangblogs/gojwt"
	"math/rand"
	"net/http"
	"pro/global"
	"pro/internal/models"
	"pro/internal/params"
	"time"
)

func SendSms(c *gin.Context) {
	var err error
	var req params.SendSmsReq

	if err = c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	if len(req.Mobile) != 11 {
		c.JSON(400, gin.H{"error": "手机号格式不正确"})
		return
	}

	result, _ := global.Rdb.Get(global.Ctx, "smsCount"+req.Mobile).Result()
	if result >= "1" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "一分钟内只能发布一次的短信验证码"})
		return
	}

	code := rand.Intn(9000) + 100

	//sms, _ := sendSms.SendSms(req.Mobile, strconv.Itoa(code))
	//if *sms.Body.Message != "OK" {
	//	c.JSON(http.StatusInternalServerError, gin.H{"error": "短信验证码格式错误"})
	//	return
	//}

	global.Rdb.Set(global.Ctx, "sendSms"+req.Mobile, code, time.Minute*5)

	incr := global.Rdb.Incr(global.Ctx, "smsCount"+req.Mobile)
	if incr.Val() == 1 {
		global.Rdb.Set(global.Ctx, "smsCount"+req.Mobile, 1, time.Minute*1)
	}

	c.JSON(http.StatusOK, gin.H{
		"code":    200,
		"message": "短信发送成功",
	})
}

func Login(c *gin.Context) {
	var err error
	var req params.LoginReq
	var u models.User
	var ll models.LoginLog
	var ui models.UserInfo

	if err = c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	if err = u.GetUserByMobile(req.Mobile); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"message": "用户信息获取失败"})
		return
	}

	result, _ := global.Rdb.Get(global.Ctx, "sendSms"+req.Mobile).Result()
	if result != req.SmsCode {
		c.JSON(http.StatusInternalServerError, gin.H{"message": "验证码错误"})
		return
	}

	if u.ID == 0 {
		u.Mobile = req.Mobile
		if err = u.Register(); err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"message": "注册失败"})
			return
		}
	}

	newJwt := jwt.NewJWT("Token")
	claims := jwt.CustomClaims{ID: u.ID}
	token, _ := newJwt.CreateToken(claims)

	ll.UserId = int(u.ID)
	ll.Token = token
	if err = ll.CreateLL(); err != nil {
		c.JSON(400, gin.H{"message": "登录日志创建失败"})
		return
	}

	key := fmt.Sprintf("userInfo:ID:%d", u.ID)
	global.DB.Where("user_id=?", u.ID).Find(&ui)
	jsonData, _ := json.Marshal(ui)
	global.Rdb.Set(global.Ctx, key, jsonData, time.Hour)

	c.JSON(http.StatusOK, gin.H{
		"code":    200,
		"message": "登录成功",
		"Token":   token,
	})
}

func GetUserInfo(c *gin.Context) {
	var err error
	var ui models.UserInfo
	var req params.UserInfoReq

	if err = c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	if err = ui.GetUserInfoById(req.UserId); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"message": "用户信息获取失败",
		})
		return
	}
	if ui.ID == 0 {
		c.JSON(http.StatusInternalServerError, gin.H{
			"message": "该用户不存在",
		})
		return
	}

	key := fmt.Sprintf("userInfo:ID:%d", req.UserId)
	global.DB.Where("user_id=?", req.UserId).Find(&ui)
	jsonData, _ := json.Marshal(ui)
	global.Rdb.Set(global.Ctx, key, jsonData, time.Hour)

	c.JSON(http.StatusOK, gin.H{
		"code":    200,
		"message": "用户个人信息展示成功",
		"data":    ui,
	})
}

func UpdateUserInfo(c *gin.Context) {
	var err error
	var ui models.UserInfo
	var req params.UpdateUserInfo

	if err = c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	ui.NickName = req.NickName
	ui.Image = req.Image
	ui.Age = req.Age
	ui.Email = req.Email
	if err = ui.UpdateUserInfo(req.UserId); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code": 400,
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code":    200,
		"message": "用户信息更新成功",
	})
}
